# -*- coding: UTF-8 -*-
import tkinter as tk
from tkinter import ttk
from Code.Utils.sc_func import Common
from Code.View.Datamation.sc_provide import view_gate
from Code.View.sc_global import Global
from Code.View.sc_base import TopWinBase
from Code.View.sc_module import WidgetTip, LabelEntry, LabelCombobox, TitleFrame

language_data = view_gate.query_language_data


class SettingsTop(TopWinBase):
    """ 首选项界面 """

    def pack(self):
        width, height = Global.G_LGN_WIN_WIDTH, Global.G_LGN_WIN_HEIGHT
        self.resize(width, height)
        self.topping(True)
        master = TitleFrame(self.master, width=width, height=height).master()
        notebook = ttk.Notebook(master, width=width, height=height-80)
        notebook.pack()
        btn_fm = tk.Frame(master)
        btn_fm.pack(fill='x')

        tool_fm = tk.Frame(notebook)
        tool_fm.pack(fill='both')
        svr_fm = tk.Frame(notebook)
        svr_fm.pack(fill='both')
        notebook.add(tool_fm, text='  {}  '.format(language_data('TOOLS', 'SETTINGS')))
        notebook.add(svr_fm, text='  {}  '.format(language_data('SERVER', 'SETTINGS')))

        settings = view_gate.query_settings_data
        self.pure_mode = LabelCombobox(tool_fm, language_data('PURE_MODE'), ['Yes', 'No'],
                                       settings('pure_mode_switch'), row=0)
        self.tool_alias = LabelEntry(tool_fm, language_data('TOOL_ALIAS'), settings('tool_alias'), row=1)
        self.tool_version = LabelEntry(tool_fm, language_data('TOOL_VERSION'), settings('tool_version'), row=2)
        self.language_type = LabelCombobox(tool_fm, language_data('TOOL_LANGUAGE'), view_gate.query_lang_types_data(),
                                           settings('language_type'), row=3)
        self.log_level = LabelCombobox(tool_fm, language_data('LOG_LEVEL'), ['debug', 'info', 'warn', 'error'],
                                       settings('log_level'), row=4)
        self.count_limit = LabelCombobox(tool_fm, language_data('MAX_SERVER_LOGIN'), list(range(1, 21)),
                                         settings('login_count_limit'), row=5)
        self.retry_times = LabelCombobox(tool_fm, language_data('FAILED_RETRY_TIMES'), list(range(1, 10)),
                                         settings('retry_times'), row=6)
        self.refresh_json = LabelCombobox(tool_fm, language_data('CONF_REFRESH_PERIOD'), [2, 5, 10, 20, 30, 60],
                                          settings('refresh_json_period'), row=7)
        self.auto_plot = LabelCombobox(tool_fm, language_data('AUTO_CHART_PERIOD'), [0, 10, 20, 30, 40, 50, 60],
                                       settings('auto_plot_period'), row=8)
        self.auto_task = LabelCombobox(tool_fm, language_data('AUTO_TASK_PERIOD'), [0, 10, 20, 30, 40, 50, 60],
                                       settings('auto_task_period'), row=9)

        default_passwords = settings('default_passwords')
        self.prefer_sw = LabelCombobox(svr_fm, '{} IP'.format(language_data('SAVE', 'SERVER')), ['Yes', 'No'],
                                       settings('preference_switch'), row=0)
        self.user_name = LabelEntry(svr_fm, language_data('SERVER', 'USER_NAME'), default_passwords[0], row=1)
        self.user_password = LabelEntry(svr_fm, language_data('SERVER', 'USER_PASSWORD'), default_passwords[1], row=2)
        self.root_password = LabelEntry(svr_fm, language_data('SERVER', 'ROOT_PASSWORD'), default_passwords[2], row=3)
        self.server_home = LabelEntry(svr_fm, language_data('SERVER', 'DIRECTORY'), settings('server_dir'), row=4)
        self.sshd_port = LabelEntry(svr_fm, language_data('SERVER', 'SSHD_PORT'), settings('sshd_port'), row=5)
        self.keepalive_period = LabelCombobox(svr_fm, language_data('SSHD_KEEPALIVE_PERIOD'),
                                              [5, 10, 20, 30, 60, 120, 180, 300],
                                              settings('keepalive_period'), row=6)

        btn_style = {'master': btn_fm,
                     'width': 14,
                     'style': "Settings.TButton"}
        ttk.Button(text=language_data('CONFIRM'), command=self.confirm, **btn_style
                   ).pack(side='left', padx=80, pady=10)
        ttk.Button(text=language_data('CANCEL'), command=self.close, **btn_style
                   ).pack(side='right', padx=80, pady=10)

    def confirm(self, event=None):
        self.topping(False)
        # check invalid
        _server_dir = self.server_home.get()
        if len(Common.normal_path(_server_dir).split('/')) < 3:
            WidgetTip.error(language_data('SERVER', 'DIRECTORY', 'LEAST_TWO_LEVEL'))
            return

        data = {
            'tool_alias': self.tool_alias.get(),
            'tool_version': self.tool_version.get(),
            'language_type': self.language_type.get(),
            'log_level': self.log_level.get(),
            'login_count_limit': int(self.count_limit.get()),
            'retry_times': int(self.retry_times.get()),
            'keepalive_period': int(self.keepalive_period.get()),
            'refresh_json_period': int(self.refresh_json.get()),
            'auto_plot_period': int(self.auto_plot.get()),
            'auto_task_period': int(self.auto_task.get()),
            'preference_switch': self.prefer_sw.get(),
            'pure_mode_switch': self.pure_mode.get(),
            'sshd_port': int(self.sshd_port.get()),
            'server_home': _server_dir,
            'passwords': {}
        }
        data['passwords']['username'] = self.user_name.get()
        data['passwords']['userpassword'] = self.user_password.get()
        data['passwords']['rootpassword'] = self.root_password.get()

        if self.prefer_sw.get() == 'No':
            data['preference_ip'] = []

        view_gate.update_settings_data.set_data(data)
        WidgetTip.info(language_data("SUCCESS"))
        self.close()
